﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using Viewer.BusinessObject.BusinessEntities;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.IO;

namespace Viewer.BaoCao
{
    public partial class BaoCaoToChucHanhChinh : System.Web.UI.Page
    {
        NSToChuc query = new Viewer.BusinessObject.BusinessEntities.NSToChuc();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                LoadDataForTree();
            }
        }
        [DirectMethod]
        public void LoadDataForTree()
        {
            //Load Root  
            
            Ext.Net.TreeNode root = new Ext.Net.TreeNode("0", "Tổ Chức Hành Chính", Icon.Folder);
            root.Expanded = true;
            root.Disabled = true;

            TreePanel.Root.Add(root);

            List<CHToChucHanhChinh> lstToChuc = (new CHToChucHanhChinh()).GetAll();

            var lstToChucLv0 = (from m in lstToChuc
                                where m.ToChucHanhChinhLevel == 0
                                select m).ToList();

            foreach (var oToChucLv0 in lstToChucLv0)
            {
                var nodeLv0 = CreateNode(oToChucLv0);
                root.Nodes.Add(nodeLv0);

                List<CHToChucHanhChinh> lstToChucLv1 = lstToChuc.Where(c => c.ToChucHanhChinhIDCha == oToChucLv0.ToChucHanhChinhID).ToList();

                foreach (var oToChucLv1 in lstToChucLv1)
                {
                    var nodeLv1 = CreateNode(oToChucLv1);
                    nodeLv0.Nodes.Add(nodeLv1);
                    List<CHToChucHanhChinh> lstToChucLv2 = lstToChuc.Where(c => c.ToChucHanhChinhIDCha == oToChucLv1.ToChucHanhChinhID).ToList();
                    foreach (var oToChucLv2 in lstToChucLv2)
                    {
                        var nodeLv2 = CreateNode(oToChucLv2);
                        nodeLv1.Nodes.Add(nodeLv2);
                        List<CHToChucHanhChinh> lstToChucLv3 = lstToChuc.Where(c => c.ToChucHanhChinhIDCha == oToChucLv2.ToChucHanhChinhID).ToList();
                        foreach (var oToChucLv3 in lstToChucLv3)
                        {
                            var nodeLv3 = CreateNode(oToChucLv3);
                            nodeLv2.Nodes.Add(nodeLv3);
                        }
                    }
                }
            }
            if (X.IsAjaxRequest)
            {
                Ext.Net.X.AddScript("refreshTree({0},{1});", TreePanel.ClientID, TreePanel.Root.ToJson());
            }
        }

        private Ext.Net.TreeNode CreateNode(CHToChucHanhChinh oToChuc)
        {
            Ext.Net.TreeNode node = new Ext.Net.TreeNode(oToChuc.ToChucHanhChinhID.ToString(), oToChuc.TenToChucHanhChinh, Icon.Group);
            node.Expanded = false;
            return node;
        }
        private List<QUNhomQuyenByToChuc_ToChuc> _nhomquyen;
        public List<QUNhomQuyenByToChuc_ToChuc> NhomQuyenByToChuc_ToChuc
        {
            get
            {
                if (_nhomquyen == null)
                {
                    //var oNguoidung = QUNguoiDung.GetByUserName(Page.User.Identity.Name.ToString());
                    //_nhomquyen = oNguoidung.NhomQuyenByToChuc_ToChuc();
                    _nhomquyen = (List<QUNhomQuyenByToChuc_ToChuc>)Session["NhomQuyenByToChuc_ToChuc"];
                }
                return _nhomquyen;
            }
        }

        /// <summary>
        /// Create TreeNode
        /// </summary>
        /// <param name="oToChuc"></param>
        /// <returns></returns>
        private Ext.Net.TreeNode CreateNode(NSToChuc oToChuc)
        {

            //Hard code for admin 
            if (Context.User.Identity.Name.ToLower() == "admin")
            {
                return CreateEnableNode(oToChuc, true, true, true, true);
            }
            bool IsView = false;
            bool IsAdd = false;
            bool IsEdit = false;
            bool IsDelete = false;
            //1 nguoi thuoc nhieu nhom quyen
            if (this.NhomQuyenByToChuc_ToChuc == null)
            {
                return CreateDisableNode(oToChuc.ToChucID.ToString(), oToChuc.TenToChucFull);
            }
            var lstNhomQuyenByToChuc_ToChuc = (from m in this.NhomQuyenByToChuc_ToChuc
                                               where m.ToChucID == oToChuc.ToChucID
                                               select m).ToList();
            if (lstNhomQuyenByToChuc_ToChuc.Count == 0)
            {
                //khong co quyen doi voi to chuc nay
                return CreateDisableNode(oToChuc.ToChucID.ToString(), oToChuc.TenToChucFull);
            }

            foreach (var item in lstNhomQuyenByToChuc_ToChuc)
            {
                IsView = IsView || item.IsView;
                IsAdd = IsAdd || item.IsAdd;
                IsEdit = IsEdit || item.IsEdit;
                IsDelete = IsDelete || item.IsDelete;

            }

            /////////////////
            if (!IsView)
            {
                return CreateDisableNode(oToChuc.ToChucID.ToString(), oToChuc.TenToChucFull);
            }

            return CreateEnableNode(oToChuc, IsView, IsAdd, IsEdit, IsDelete);
        }

        private Ext.Net.TreeNode CreateEnableNode(NSToChuc oToChuc, bool IsView, bool IsAdd, bool IsEdit, bool IsDelete)
        {
            Ext.Net.TreeNode node = new Ext.Net.TreeNode(oToChuc.ToChucID.ToString(), oToChuc.TenToChucFull, Icon.Group);
            node.CustomAttributes.Add(new ConfigItem("IsView", IsView ? "1" : "0"));
            node.CustomAttributes.Add(new ConfigItem("IsAdd", IsAdd ? "1" : "0"));
            node.CustomAttributes.Add(new ConfigItem("IsEdit", IsEdit ? "1" : "0"));
            node.CustomAttributes.Add(new ConfigItem("IsDelete", IsDelete ? "1" : "0"));

            node.Expanded = true;
            return node;
        }

        /// <summary>
        /// Create a disable treenode
        /// </summary>
        /// <param name="id"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        private Ext.Net.TreeNode CreateDisableNode(string id, string text)
        {
            Ext.Net.TreeNode node = new Ext.Net.TreeNode(id + "Decline", text, Icon.GroupKey);
            node.CustomAttributes.Add(new ConfigItem("IsView", "0"));
            node.Disabled = true;
            node.Cls = "Disable";
            node.Expanded = true;
            return node;
        }

        protected void Menu_Report(object sender, DirectEventArgs e)
        {
            //string type = e.ExtraParams["ReportType"].ToString();

            //NSToChuc oToChucCha = (new NSToChuc()).GetByID(int.Parse(__currentNode.Text));
            //List<NSToChuc> lstToChucCon = NSToChuc.GetToChucCon(oToChucCha.ToChucID);

            //var lstTochucConIDs = (from m in lstToChucCon
            //                       select m.ToChucID).ToList();
            List<int> lstTochucConIDs = new List<int>();
            lstTochucConIDs.Add(int.Parse(__currentNode.Text));
            int rowNumber = lstTochucConIDs.Count;
            object[,] dataArr = new object[rowNumber, 165];
            ////Intital data
            //for (int i = 0; i < rowNumber; i++)
            //{
            //    dataArr[i, 0] = i + 1;
            //    dataArr[i, 3] = lstToChucCon[i].TenToChucFull;
            //    for (int j = 4; j < dataArr.GetLength(1); j++)
            //    {
            //        dataArr[i, j] = string.Empty;
            //    }
            //}

            //Insert data from databases into dataArr
            //Duyet tung cot
            for (int i = 0; i < rowNumber; i++)
            {
                var rowItem = CHToChucHanhChinh.Report(lstTochucConIDs[i]);
                int level= (new CHToChucHanhChinh()).GetByID(lstTochucConIDs[i]).ToChucHanhChinhLevel;
                if (level == 0)
                {
                    dataArr[i, 1] = rowItem.TenToChucFull;
                }
                else if (level ==1)
                {
                    dataArr[i, 2] = rowItem.TenToChucFull;
                }
                else if (level ==2)
                {
                            dataArr[i, 3] = rowItem.TenToChucFull;
                    
                    }
                
                dataArr[i, 10] = rowItem.Nu;
                dataArr[i, 11] = rowItem.DangVien;
                dataArr[i, 12] = rowItem.DanTocItNguoi;
                dataArr[i, 13] = rowItem.Duoi30Tuoi;
                dataArr[i, 14] = rowItem.Tuoi30_50;
                dataArr[i, 15] = rowItem.Tuoi51_60;
                dataArr[i, 16] = rowItem.Nu_54Tuoi;
                dataArr[i, 17] = rowItem.Nam_59Tuoi;
                dataArr[i, 19] = rowItem.LLCT_CaoCap;
                dataArr[i, 20] = rowItem.LLCT_TrungCap;
                dataArr[i, 21] = rowItem.LLCT_SoCap;
                dataArr[i, 22] = rowItem.AnhVan_CuNhan;
                dataArr[i, 23] = rowItem.AnhVan_CoSo;
                dataArr[i, 24] = rowItem.NNKhac_CuNhan;
                dataArr[i, 25] = rowItem.NNKhac_CoSo;
                dataArr[i, 26] = rowItem.TinHoc_CuNhan;
                dataArr[i, 27] = rowItem.TinHoc_CoSo;
                dataArr[i, 28] = rowItem.ThayThuocNhanDan;
                dataArr[i, 29] = rowItem.ThayThuocUuTu;
                dataArr[i, 30] = rowItem.NhaGiaoNhanDan;
                dataArr[i, 31] = rowItem.NhaGiaoUuTu;
                dataArr[i, 44] = rowItem.TongSoBacSi;
                dataArr[i, 45] = rowItem.TongSoBacSi_Nu;

                dataArr[i, 46] = rowItem.GiaoSuY;
                dataArr[i, 47] = rowItem.GiaoSuY_Nu;
                dataArr[i, 48] = rowItem.PhoGiaoSuY;
                dataArr[i, 49] = rowItem.PhoGiaoSuY_Nu;
                dataArr[i, 50] = rowItem.TienSiY;
                dataArr[i, 51] = rowItem.TienSiY_Nu;

                dataArr[i, 52] = rowItem.ThacSiY;
                dataArr[i, 53] = rowItem.ThacSiY_Nu;

                dataArr[i, 54] = rowItem.BacSiCK2;
                dataArr[i, 55] = rowItem.BacSiCK2_Nu;

                dataArr[i, 56] = rowItem.BacSiCK1;
                dataArr[i, 57] = rowItem.BacSiCK1_Nu;

                dataArr[i, 59] = rowItem.BacSiNha;
                dataArr[i, 60] = rowItem.BacSiNha_Nu;

                dataArr[i, 62] = rowItem.ChuyenVienCaoCap;
                dataArr[i, 63] = rowItem.ChuyenVienChinh;

                dataArr[i, 64] = rowItem.ChuyenVien;
                dataArr[i, 65] = rowItem.BacSiCaoCap;

                dataArr[i, 66] = rowItem.BacSiChinh;
                dataArr[i, 67] = rowItem.BacSi;

                dataArr[i, 69] = rowItem.DuocSiDaiHoc;
                dataArr[i, 70] = rowItem.DuocSiDaiHoc_Nu;

                dataArr[i, 71] = rowItem.GiaoSuDuoc;//BT
                dataArr[i, 72] = rowItem.GiaoSuDuoc_Nu;
                dataArr[i, 73] = rowItem.PhoGiaoSuDuoc;
                dataArr[i, 74] = rowItem.PhoGiaoSuDuoc_Nu;
                dataArr[i, 75] = rowItem.TienSiDuoc;
                dataArr[i, 76] = rowItem.TienSiDuoc_Nu;
                dataArr[i, 77] = rowItem.ThacSiDuoc;
                dataArr[i, 78] = rowItem.ThacSiDuoc_Nu;
                dataArr[i, 79] = rowItem.DuocSiCK2;
                dataArr[i, 80] = rowItem.DuocSiCK2_Nu;
                dataArr[i, 81] = rowItem.DuocSiCK1;
                dataArr[i, 82] = rowItem.DuocSiCK1_Nu;

                dataArr[i, 85] = rowItem.NgachDuocSi_ChuyenVienCaoCap;
                dataArr[i, 86] = rowItem.NgachDuocSi_ChuyenVienChinh;
                dataArr[i, 87] = rowItem.NgachDuocSi_ChuyenVien;
                dataArr[i, 88] = rowItem.NgachDuocSiCaoCap;
                dataArr[i, 89] = rowItem.NgachDuocSiChinh;
                dataArr[i, 90] = rowItem.NgachDuocSi;
                dataArr[i, 92] = rowItem.ThacSiYTeCongCong;
                dataArr[i, 93] = rowItem.ThacSiYTeCongCong_Nu;
                dataArr[i, 94] = rowItem.DaiHocYTeCongCong;
                dataArr[i, 95] = rowItem.DaiHocYTeCongCong_Nu;
                dataArr[i, 96] = rowItem.NgachYTeCongCongChinh;
                dataArr[i, 97] = rowItem.NgachYTeCongCong;
                dataArr[i, 98] = rowItem.YSi;
                dataArr[i, 99] = rowItem.YSi_Nu;
                dataArr[i, 100] = rowItem.NgachYSi;
                dataArr[i, 101] = rowItem.NgachYSiCanSu;

                dataArr[i, 103] = rowItem.KTVNhaKhoa;
                dataArr[i, 104] = rowItem.KTVNhaKhoa_Nu;
                dataArr[i, 105] = rowItem.NgachKTVNhaKhoa;
                dataArr[i, 106] = rowItem.KTVY;
                dataArr[i, 107] = rowItem.KTVY_Nu;
                dataArr[i, 108] = rowItem.KTVYDaiHoc;
                dataArr[i, 109] = rowItem.KTVYCaoDang;
                dataArr[i, 110] = rowItem.KTVYTrungHoc;
                dataArr[i, 111] = rowItem.KTVYSoHoc;
                dataArr[i, 112] = rowItem.NgachKTVYChinh;
                dataArr[i, 113] = rowItem.NgachKTVY;
                dataArr[i, 114] = rowItem.NgachKTVYCaoDang;
                dataArr[i, 115] = rowItem.NgachKTVYTrungHoc;
                dataArr[i, 116] = rowItem.NgachKTVYSoHoc;

                dataArr[i, 117] = rowItem.DuocSiTH_KTVTrungHocDuoc;
                dataArr[i, 118] = rowItem.DuocSiTH_KTVTrungHocDuoc_Nu;
                dataArr[i, 119] = rowItem.NgachDuocSiTH;
                dataArr[i, 120] = rowItem.DieuDuong;
                dataArr[i, 121] = rowItem.DieuDuong_Nu;
                dataArr[i, 122] = rowItem.DieuDuongDaiHoc;
                dataArr[i, 123] = rowItem.DieuDuongCaoDang;
                dataArr[i, 124] = rowItem.DieuDuongTrungHoc;
                dataArr[i, 125] = rowItem.DieuDuongSoHoc;
                dataArr[i, 126] = rowItem.NgachDieuDuongChinh;
                dataArr[i, 127] = rowItem.NgachDieuDuong;
                dataArr[i, 128] = rowItem.NgachDieuDuongCaoDang;
                dataArr[i, 129] = rowItem.NgachDieuDuongTrungCap;
                dataArr[i, 130] = rowItem.NgachDieuDuongSoCap;
                dataArr[i, 131] = rowItem.HoSinh;
                dataArr[i, 132] = rowItem.HoSinh_Nu;
                dataArr[i, 133] = rowItem.HoSinhDaiHoc;
                dataArr[i, 134] = rowItem.HoSinhCaoDang;
                dataArr[i, 135] = rowItem.HoSinhTrungHoc;
                dataArr[i, 136] = rowItem.HoSinhSoHoc;
                dataArr[i, 137] = rowItem.NgachHoSinhChinh;
                dataArr[i, 138] = rowItem.NgachHoSinh;
                dataArr[i, 139] = rowItem.NgachHoSinhCaoDang;
                dataArr[i, 140] = rowItem.NgachHoSinhTrungCap;
                dataArr[i, 141] = rowItem.NgachHoSinhSoCap;
                dataArr[i, 142] = rowItem.LuongY;
                dataArr[i, 143] = rowItem.LuongY_Nu;
                dataArr[i, 144] = rowItem.DuocTa;
                dataArr[i, 145] = rowItem.DuocTa_Nu;
                dataArr[i, 146] = rowItem.NgachDuocTa;

                dataArr[i, 147] = rowItem.TDCMSauDaiHoc;
                dataArr[i, 148] = rowItem.TDCMSauDaiHoc_Nu;
                dataArr[i, 149] = rowItem.TDCMDaiHoc;
                dataArr[i, 150] = rowItem.TDCMDaiHoc_Nu;

                dataArr[i, 151] = rowItem.TDCMCaoDang;
                dataArr[i, 152] = rowItem.TDCMCaoDang_Nu;
                dataArr[i, 153] = rowItem.TDCMTrungHoc;
                dataArr[i, 154] = rowItem.TDCMTrungHoc_Nu;
                dataArr[i, 156] = rowItem.NgachCBKhacChuyenVienCaoCap;
                dataArr[i, 157] = rowItem.NgachCBKhacChuyenVienChinh;
                dataArr[i, 158] = rowItem.NgachCBKhacChuyenVien;
                dataArr[i, 159] = rowItem.NgachCBKhacCanSu;
                dataArr[i, 160] = rowItem.NgachCBKhacNhanVien;
            }
            //Export
            ExportToExcel(dataArr, 1);
        }

        /// <summary>
        /// Export To Excel
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="sheetIndex"></param>
        private void ExportToExcel(object[,] arr, int sheetIndex)
        {
            object misValue = System.Reflection.Missing.Value;
            string templatePath = Server.MapPath("~/Baocao/Template/template.xls");
            string newFileName = Context.User.Identity.Name + DateTime.Now.ToString("dd_MM_yyyy_ss") + ".xls";
            string temporaryFilePath = Server.MapPath("~/BaoCao/Template/") + newFileName;
            try
            {
                if (arr == null)
                {
                    throw new Exception("No data inserted");
                }
                if (!File.Exists(templatePath))
                {
                    throw new Exception("Template khong ton tai o dia chi" + templatePath);
                }

                System.IO.FileInfo file = new System.IO.FileInfo(templatePath);
                file.CopyTo(temporaryFilePath);

                Excel.Application xlApp;
                Excel.Workbook xlWorkBook;
                Excel.Worksheet xlWorkSheet;

                //Excel.Range copyFormatRange;
                //Create File

                xlApp = new Excel.ApplicationClass();
                if (xlApp == null)
                {
                    throw new Exception("Excel could not be started. Check that your office installation and project references are correct.");
                }
                xlWorkBook = xlApp.Workbooks.Open(temporaryFilePath, misValue, misValue, misValue, misValue, misValue, misValue,
                    misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);

                //select Sheet
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(sheetIndex);
                //Insert Data to the file
                int row = arr.GetLength(0);
                int column = arr.GetLength(1);
                if (row > 0)
                {
                    //copyFormatRange = xlWorkSheet.get_Range("A10", "FI10");
                    //copyFormatRange.Select();
                    //copyFormatRange.Copy(Type.Missing);

                    //for (int i = 0; i < row; i++)
                    //{
                    //    copyFormatRange.Insert(Excel.XlInsertShiftDirection.xlShiftDown, true);
                    //}
                    //xlWorkSheet.Cells[9, 10] = string.Format("=Sum(J{0}:J{1})", 10, 10 + row - 1);

                    int topRow = 10;
                    Excel.Range c1 = (Excel.Range)xlWorkSheet.Cells[topRow, 1];
                    Excel.Range c2 = (Excel.Range)xlWorkSheet.Cells[topRow + row - 1, column];
                    Excel.Range range = xlWorkSheet.get_Range(c1, c2);

                    range.Value2 = arr;
                }



                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();

                ReleaseComObject(xlWorkSheet);
                ReleaseComObject(xlWorkBook = null);
                ReleaseComObject(xlApp);
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

                byte[] document = this.StreamFile(temporaryFilePath);
                Response.Clear();
                Response.Charset = "UTF-8";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.Cache.SetNoServerCaching();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + newFileName);
                Response.ContentType = "application/ms-excel";
                Response.BinaryWrite(document);
                Response.End();

            }
            catch (Exception)
            {
                throw;
            }
        }
        private static void ReleaseComObject(object activeXObject)
        {
            if (activeXObject != null)
            {
                Marshal.ReleaseComObject(activeXObject);
                activeXObject = null;
            }
        }

        private byte[] StreamFile(string filename)
        {
            byte[] ImageData = new byte[0];
            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            try
            {
                ImageData = new byte[fs.Length];
                fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
                System.IO.FileInfo file1 = new System.IO.FileInfo(filename);
                file1.Delete();
            }
            return ImageData;
        }

    }
}
